package com.yj.timecapsule.service.comments.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yj.timecapsule.common.enums.ErrorCode;
import com.yj.timecapsule.common.error.BusinessException;
import com.yj.timecapsule.common.response.PageResponse;
import com.yj.timecapsule.entity.user.Users;
import com.yj.timecapsule.entity.comments.Comments;
import com.yj.timecapsule.entity.comments.dto.CommentDto;
import com.yj.timecapsule.entity.comments.dto.CommentPageDto;
import com.yj.timecapsule.entity.comments.vo.CommentsVo;
import com.yj.timecapsule.mapper.CommentsMapper;
import com.yj.timecapsule.service.comments.CommentsService;
import com.yj.timecapsule.service.user.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentsServiceImpl implements CommentsService {
    @Resource
    private CommentsMapper commentsMapper;
    @Resource
    private UserService userService;
    @Override
    public PageResponse<CommentsVo> list(CommentPageDto dto) {
        PageHelper.startPage(dto.getPage(),dto.getSize());
        Page<Comments> commentsPage = commentsMapper.selectByDiariesId(dto.getDiariesId());
        List<CommentsVo> commentsVoList = buildCommentTree(commentsPage.getResult());

        return PageResponse.create(commentsPage.getTotal(), commentsVoList);
    }

    @Override
    public void comment(CommentDto commentDto) {
        Comments comments = new Comments();
        BeanUtil.copyProperties(commentDto,comments);
        commentsMapper.insertSelective(comments);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(Long id) {
        if (id == null){
            throw new BusinessException(ErrorCode.FAIL);
        }
        commentsMapper.deleteByPrimaryKey(id);
        List<Comments> comments = commentsMapper.selectByParentId(id);
        List<Long> ids = new ArrayList<>();
        for (int i = 0; i < comments.size(); i++) {
            Long l = comments.get(i).getId();
            ids.add(l);
        }
        commentsMapper.deleteByIds(ids);
    }

    private List<CommentsVo> buildCommentTree(List<Comments> comments) {
        List<CommentsVo> commentsVoList = BeanUtil.copyToList(comments, CommentsVo.class);
        commentsVoList.forEach(vo -> {
            Users user = userService.getInfo(vo.getUserId());
            if (user != null){
                vo.setUserName(user.getUsername());
            }
            // 获取子评论
            List<Comments> childComments = commentsMapper.selectByParentId(vo.getId());
            List<CommentsVo> childCommentVoList = buildCommentTree(childComments);
            vo.setChildComments(childCommentVoList);
        });
        return commentsVoList;
    }
}
